<template>
  <div class="homebox">
    <!-- <div class=""></div> -->
    <Headmain :ymbsid="ymbsid" />
    <div class="date-switcher">
      <!-- <button @click="changeDate(-1)">◀</button> -->
      <span class="date-display">{{ formattedDate }}</span>
      <!-- <button @click="changeDate(1)">▶</button> -->
    </div>
    <!-- 数据概览 -->
    <div class="desbox">
      <div class="desbox1">
        排版概括：
        <div class="bsdiv1"></div>
        <div>已结束</div>
        <div class="bsdiv2"></div>
        <div>未开始</div>
        <div class="bsdiv3"></div>
        <div>锁定</div>
      </div>
      <div class="desbox1">
        未到人员：
        <div class="namebox">
          <span v-for="(item, index) in noSigndata" :key="index">
            {{ item.patientName
            }}<span v-if="index < noSigndata.length - 1">, </span>
          </span>
        </div>
        <div class="namemovebt" @click="moveshow = true">查看更多</div></div
      >
    </div>
    <!-- 查看详情概览 -->
    <a-modal v-model:visible="moveshow">
      <template #title>详情</template>
      <div class="movebox">
        <a-table :columns="columns" :data="noSigndata" />
      </div>
    </a-modal>
    <!-- 日排版 显示 -->
    <div class="daybox" v-if="!addFormshow">
      <div class="dayboxleft">
        <div class="dayboxlefttop">时间段</div>
        <div class="dayboxbottom">患者</div>
      </div>
      <div class="dayboxright beautifulScroll">
        <div class="dayboxrighttop">
          <div
            class="daytimeitem"
            v-for="(item, index) in timerdata"
            :key="index"
            >{{ item }}</div
          >
        </div>
        <div class="dayboxrightbottom">
          <div
            class="dayboxbottomitem"
            v-for="(item, index) in timerdata"
            :key="index"
          >
            <div
              v-if="matchedData[item]?.length && checkTime(item) == '时间可用'"
            >
              <div
                @click="gohuanzhe(entry)"
                v-for="(entry, idx) in matchedData[item]"
                :key="idx"
                class="patient-item"
                :class="
                  idx < matchedData[item].length - 1 || idx == 0
                    ? 'patient-items'
                    : ''
                "
              >
                <div>{{ entry.patientName }}（未开始）</div>
              </div>
            </div>
            <div v-else class="no-data">{{
              checkTime(item) == '时间已锁定' ? '时间已锁定' : '暂无患者'
            }}</div>
          </div>
        </div>
      </div>
    </div>
    <!-- 患者详细信息 -->
    <div class="container" v-if="addFormshow">
      <div @click="addFormshow = false" style="cursor: pointer; color: #297eff"
        >返回上一步</div
      >
      <!-- 患者详情 -->
      <a-card title="患者信息">
        <a-form ref="addModel" :model="addForm">
          <a-row style="display: flex !important">
            <a-col :span="8">
              <a-form-item field="patientName" label="姓名：">
                {{ addForm.patientName }}</a-form-item
              ></a-col
            >
            <a-col :span="8"
              ><a-form-item field="idCard" label="身份证号：">
                {{ addForm.idCard }}</a-form-item
              ></a-col
            >
            <a-col :span="8">
              <a-form-item field="patientSex" label="性别：">
                {{ addForm.patientSex == 'F' ? '男' : '女' }}</a-form-item
              ></a-col
            >
          </a-row>
          <a-row style="display: flex !important; flex-flow: nowrap">
            <a-form-item field="patientAge" label="患者年龄：">
              {{ addForm.patientAge }}
            </a-form-item>
            <a-form-item field="mobile" label="手机号：">
              {{ addForm.mobile }}
            </a-form-item>
            <a-form-item> </a-form-item>
          </a-row>
        </a-form>
      </a-card>

      <a-card title="预约信息">
        <a-form ref="addModel" :model="addForm">
          <a-row style="display: flex !important">
            <a-col :span="8">
              <a-form-item field="patientName" label="姓名：">
                {{ addForm.patientName }}</a-form-item
              ></a-col
            >
            <a-col :span="8"
              ><a-form-item field="idCard" label="预约时间：">
                {{ addForm.date }}</a-form-item
              ></a-col
            >
            <a-col :span="8">
              <a-form-item label="是否已签到:">
                {{
                  addForm.signStatus == '9' ? '未签到' : '已签到'
                }}</a-form-item
              ></a-col
            >
          </a-row>
        </a-form>
      </a-card>
      <a-card title="治疗评估">
        <a-table
          ref="userList"
          row-key="userId"
          :loading="loading"
          page-position="bottom"
          :pagination="pagination"
          :row-selection="rowSelection"
          v-model:selectedKeys="userIds"
          :columns="column"
          :data="renderData"
          :bordered="false"
          @page-change="onPageChange"
          @page-size-change="onPageSizeChange"
        >
          <template #treatmentPlanId="{ record }">
            <div style="color: blue" @click="goevaluation(record)">详情</div>
          </template>
        </a-table>
      </a-card>
      <div class="signbox" @click="signfn" v-if="addForm.signStatus == '9'"
        ><div>手动确认</div><div>患者签到</div></div
      >
      <!-- 是否 addForm.signStatus -->
      <div class="signbox" @click="signfn" v-if="addForm.signStatus != '9'"
        ><div>后续预约</div></div
      >
      <!-- 弹窗提示确认 -->
      <a-modal
        :visible="visibleshow"
        @ok="handleOk"
        okText="不需要了"
        cancelText="继续治疗"
        unmountOnClose
      >
        <template #title> 提示 </template>
        <div>该病患是否需要继续治疗？</div>
      </a-modal>
    </div>
    <!-- 治疗评判 -->
    <a-modal
      v-model:visible="Evaluationshow"
      :mask-closable="false"
      unmountOnClose
      width="800px"
    >
      <template #title> 治疗项目</template>
      <div class="zlbox">
        <div class="table">
          <div class="row">
            <div class="cell cellpjt">治疗师信息</div>
            <div class="cell colspan-4 divd">
              <div>分组:</div>
              <div>治疗师:</div>
              <!-- <div>提交时间2024-11-27 11:08</div> -->
            </div>
          </div>
          <div class="row">
            <div class="cell cellpjt">综合评判</div>
            <div class="cell colspan-4">
              {{ Evaluationdata.evaluation }}
            </div>
          </div>

          <div v-for="(item, index) in Evaluationdata.list" :key="index">
            <div class="row">
              <div class="cell colspan-4">治疗内容项目</div>
              <div class="cell cellpj">优秀</div>
              <div class="cell cellpj">良好</div>
              <div class="cell cellpj">较差</div>
            </div>
            <div class="row">
              <div class="cell colspan-4">{{ item.content }}</div>
              <div class="cell cellpj"
                ><icon-check style="color: green" v-if="item.good == 1"
              /></div>
              <div class="cell cellpj"
                ><icon-check style="color: green" v-if="item.poor == 1"
              /></div>
              <div class="cell cellpj"
                ><icon-check style="color: green" v-if="item.good == 1"
              /></div>
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed } from 'vue';
  import Headmain from '../headmain/headmain.vue';
  import {
    noSign,
    getTimeList,
    dayPlan,
    patientInfo,
    sign,
    saveEvaluation,
    evaluationList,
    evaluation,
    stopTreatment,
    restList,
  } from '@/api/home';
  import useLoading from '@/hooks/loading';
  import { Message, Modal } from '@arco-design/web-vue';
  import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
  const { loading, setLoading } = useLoading(true);
  const resttimer = ref([]);
  import { useRoute } from 'vue-router';
  import { dataTool } from 'echarts';
  const route = useRoute();
  console.log('查询日期', route.query.date);

  const restListfn = (startDate: Date, endDate: Date) => {
    restList({
      pageNum: 1,
      pageSize: 200,
      startDate: startDate,
      endDate: endDate,
    }).then((res) => {
      if (res.code == 200) {
        console.log('打印', res.data);
        resttimer.value = res.data.list;
      }
    });
  };
  // 定义当页面标识
  const ymbsid = ref('1');
  // 定义详情人概览
  const moveshow = ref(false);
  const columns = [
    {
      title: '患者姓名',
      dataIndex: 'patientName',
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
    },
  ];
  // 获取当日日期
  const currentDate = ref();
  currentDate.value = new Date(route.query.date);
  // 创建当日日期后 查询当日 未到人员
  // 定义未到人员
  const noSigndata = ref();
  const formattedDates = ref();
  const noSignfn = () => {
    const date = new Date(currentDate.value);
    // 获取所需格式的日期字符串
    formattedDates.value = `${date.getFullYear()}-${String(
      date.getMonth() + 1
    ).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    // 进行请求
    noSign({ date: formattedDates.value }).then((res) => {
      if (res.code == 200) {
        noSigndata.value = res.data;
      }
    });

    dayPlan({ date: formattedDates.value }).then((res) => {
      if (res.code == 200) {
        dayplandata.value = res.data;
        // noSigndata.value = res.data;
      }
    });
    restListfn(formattedDates.value, formattedDates.value);
  };
  noSignfn();
  // 定义获取时间段
  const timerdata = ref();
  const dayplandata = ref();
  const getTimeListfn = () => {
    getTimeList().then((res) => {
      if (res.code == 200) {
        timerdata.value = res.data;
      }
    });
  };
  getTimeListfn();
  // 格式化日期为 YYYY年MM月DD日
  const formattedDate = computed(() => {
    const year = currentDate.value.getFullYear();
    const month = String(currentDate.value.getMonth() + 1).padStart(2, '0');
    const day = String(currentDate.value.getDate()).padStart(2, '0');
    return `${year}年${month}月${day}日`;
  });

  // 修改日期
  const changeDate = (offset: number) => {
    // 创建新日期对象以替换 currentDate 的引用
    const newDate = new Date(currentDate.value);
    newDate.setDate(newDate.getDate() + offset);
    currentDate.value = newDate; // 替换引用，触发响应式更新

    // console.log('执行了修改日期', currentDate.value);
    // 修改日期后操作
    // 查询最新未到人员列表
    noSignfn();
  };

  // 匹配 dayplandata 和 timerdata
  const matchedData = computed(() => {
    const result: { [key: string]: PatientData[] } = {};
    timerdata.value.forEach((timeRange) => {
      const [start, end] = timeRange.split('-');
      result[timeRange] = [];
      Object.keys(dayplandata.value).forEach((key) => {
        if (key >= start && key < end) {
          result[timeRange].push(...dayplandata.value[key]);
        }
      });
    });
    return result;
  });

  // 去查看患者详情
  const patientTreatmentId = ref();

  const gohuanzhe = (item: any) => {
    patientTreatmentId.value = item.patientTreatmentId;
    console.log('当前患者', item);
    patientInfo({
      patientId: item.patientId,
    }).then((res) => {
      if (res.code == 200) {
        addForm.value = res.data;
        addForm.value.signStatus = item.signStatus;
        addForm.value.date =
          formattedDates.value + ' ' + item.startTime + '~' + item.endTime;
        addForm.value.patientTreatmentId = item.patientTreatmentId;
      }
    });
    fetchData();
    addFormshow.value = true;
  };
  // 查询患者的评估列表

  const fetchData = async () => {
    setLoading(true);
    try {
      evaluationList({
        patientTreatmentId: patientTreatmentId.value,
      }).then((res) => {
        if (res.code == 200) {
          renderData.value = res.data.list;
        }
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };
  // 定义患者信息
  const addForm = ref({
    createTime: '',
    createUser: '',
    idCard: '',
    mobile: '',
    patientAge: '',
    patientId: '',
    patientName: '',
    patientSex: '',
    treatment: false,
    treatmentNumber: '',
    signStatus: '',
    date: '',
    patientTreatmentId: '',
  });
  // 签到
  const signfn = () => {
    sign({
      treatmentPlanId: addForm.value.patientTreatmentId,
    }).then((res) => {
      if (res.code == 200) {
        console.log('签到成功');
      }
    });
  };
  //定义无用参数
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const pagination = reactive({
    ...basePagination,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const userIds = ref();

  const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
  };
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    fetchData();
  };
  const renderData = ref();

  const column = [
    {
      title: '评估名称',
      dataIndex: 'planTime',
    },
    {
      title: '评估时间',
      dataIndex: 'planTime',
    },
    {
      title: '治疗师',
      dataIndex: 'nickname',
    },
    {
      title: '操作',
      dataIndex: 'treatmentPlanId',
      slotName: 'treatmentPlanId',
    },
  ];
  // 查询评估详情
  const Evaluationshow = ref(false);
  const Evaluationdata = ref();
  const goevaluation = (item: { treatmentPlanId: any }) => {
    evaluation({
      treatmentPlanId: item.treatmentPlanId,
    }).then((res) => {
      if (res.code == 200) {
        Evaluationdata.value = JSON.parse(res.data);
        console.log('查询评估详情成功', Evaluationdata.value);
        Evaluationshow.value = true;
      }
    });
  };
  const addFormshow = ref(false);
  const visibleshow = ref(false);

  const handleOk = () => {
    stopTreatment({
      patientTreatmentId: addForm.value.patientTreatmentId,
    })
      .then((res) => {
        if (res.code == 200) {
        }
      })
      .catch((error) => {
        console.error('请求失败:', error);
      });
  };
  const checkTime = (item) => {
    const timeFormatRegex = /^\d{2}:\d{2}-\d{2}:\d{2}$/;
    if (!timeFormatRegex.test(item)) {
      return '时间格式不正确';
    }

    const [startTimeItem, endTimeItem] = item.split('-');

    // 从 currentDate.value 中提取日期
    const currentDateObj = new Date(currentDate.value); // 当前日期对象

    // 构造新的日期对象，使用当前日期和给定的时间
    const startDateTimeItem = new Date(
      currentDateObj.setHours(...startTimeItem.split(':').map(Number))
    );
    const endDateTimeItem = new Date(
      currentDateObj.setHours(...endTimeItem.split(':').map(Number))
    );

    // 检查日期是否有效
    if (
      isNaN(startDateTimeItem.getTime()) ||
      isNaN(endDateTimeItem.getTime())
    ) {
      return '时间格式不正确'; // 返回格式不正确的提示
    }
    if (resttimer.value.length <= 0) {
      return;
    }
    for (const rest of resttimer.value) {
      const startDateTimeRest = new Date(rest.startTime);
      const endDateTimeRest = new Date(rest.endTime);

      // 检查 item 的时间段是否与 resttimer 的时间段重叠
      if (
        (startDateTimeItem < endDateTimeRest &&
          endDateTimeItem > startDateTimeRest) || // 时间段重叠
        (startDateTimeItem >= startDateTimeRest &&
          startDateTimeItem < endDateTimeRest) || // item 开始时间在 rest 时间段内
        (endDateTimeItem > startDateTimeRest &&
          endDateTimeItem <= endDateTimeRest) || // item 结束时间在 rest 时间段内
        (startDateTimeItem <= startDateTimeRest &&
          endDateTimeItem >= endDateTimeRest) // item 完全覆盖 rest
      ) {
        return '时间已锁定';
      }
    }

    return '时间可用';
  };
</script>

<style scoped>
  .date-switcher {
    position: absolute;
    top: 20px;
    left: 50%;
    transform: translate(-50%, 0);
    display: flex;
    align-items: center;
    gap: 10px;
    font-family: Arial, sans-serif;
    z-index: 999;
  }

  .date-display {
    padding: 5px 10px;
  }

  button {
    cursor: pointer;
    padding: 5px;
    border: none;
    background-color: #007bff;
    color: white;
    border-radius: 5px;
    font-size: 14px;
  }

  button:hover {
    background-color: #0056b3;
  }
</style>
